package com.totobox.apps.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.totobox.apps.R;
import com.totobox.apps.common.ImageDownloader;
import com.totobox.apps.common.Member;
import com.totobox.apps.common.TotoIFData;
import com.totobox.apps.common.Util;

public class TotoFunActivity extends BasicActivity {
	
	private ProgressDialog progressDialog;
	final public int PROGRESS_DIALOG = 0;
	
	public Thread dataThread = null;
	public Handler handler = new Handler();
	
	public List<Map<String,String>> totocastList;
	
	public ListView totoCast;
	public FolderListAdapter listAdapter;
	
	ImageView btnGeneral;
	ImageView btnAdult;
	
	//체크 박스 리스트
	public List<CheckBox> checkList = new ArrayList<CheckBox>();
	public List<ImageView> imageList = new ArrayList<ImageView>();
	
	public boolean onOff = false;
	
	private int page = 0, totalPage = 0;
	private String bAdult = "0";
	
	
	public ImageDownloader imageDownloader = null;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.toto_fun_cast);
        
        totoCast = (ListView)findViewById(R.id.totocast_list);
        totoCast.setOnItemClickListener(this);
        
        super.initTitle();
        
        LayoutInflater inflater = getLayoutInflater();
		View v = inflater.inflate(R.layout.layout_totocast_top_menu, null);
		
		btnGeneral = (ImageView)v.findViewById(R.id.btn_general);
		btnGeneral.setPressed(true);
		btnGeneral.setOnClickListener(this);
		btnAdult = (ImageView)v.findViewById(R.id.btn_adult);
		btnAdult.setOnClickListener(this);
		
		topMenu = (LinearLayout) findViewById(R.id.layout_totocast_top_menu);
		topMenu.addView(v);

        //하단 메뉴 세팅
        super.setFooterMenu(this);
        
		showDialog(PROGRESS_DIALOG);
		
		dataThread = new Thread(null, jsonList);
    	dataThread.start();
    }

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_general){
			btnGeneral.setEnabled(false);
			btnAdult.setEnabled(true);
			btnGeneral.setPressed(true);
			btnAdult.setPressed(false);
	        
			bAdult = "0";
		}
		else if (v.getId() == R.id.btn_adult){
			if (Member.bAdult == null || Member.bAdult.equals("0")) {
				super.showText(this, "미성년자는 이용이 불가합니다.");
				return;
			}
			btnGeneral.setEnabled(true);
			btnAdult.setEnabled(false);
			btnGeneral.setPressed(false);
			btnAdult.setPressed(true);
	        
			bAdult = "1";
		}
		
		page = 0;
		totalPage = 0;
		totocastList = null;
		dataThread = new Thread(null, jsonList);
    	dataThread.start();
	}
	
	/**
	 * 토토캐스트 리스트
	 */
	private Runnable jsonList = new Runnable() {
    	public void run() {
    		try {
    			
    			//fList = new ArrayList<Map<String,String>>();
    			String iPage = page+"";
    			String biCursorSeq = "0";
    			String iPageSize = "25";
    			String bAdult = "0";
    			String vcAgent = "android";

    			totocastList = TotoIFData.TotoCast(iPage , biCursorSeq , iPageSize , bAdult, vcAgent);
    			
		    	handler.post(dataResults);
		    	
    		} catch (Exception e) {
    			Log.d("partData : ", e.toString());
    		}
    	}
    };
    
    /**
     * 
     */
	private Runnable dataResults = new Runnable() {
    	public void run() {
    		try {
    			if (totocastList != null) {
    				
    				listAdapter = new FolderListAdapter(TotoFunActivity.this , R.layout.item_folder_list ,  totocastList);
    				totoCast.setAdapter(listAdapter);
    				
    			}
    			else{
    				showNotFoundData();
    			}
    			
    	    	progressDialog.dismiss();
    	    	TotoFunActivity.this.removeDialog(PROGRESS_DIALOG);
    	    	
    		} catch (Exception e) {
    			Log.e("xml-data", e.toString());
    		}

    	}
    };
    
    private void showNotFoundData() {
    	Toast toast = Toast.makeText(this, "토토캐스트 리스트가 없습니다.", Toast.LENGTH_SHORT);
    	toast.show();
    }
    
    class FolderListAdapter extends ArrayAdapter {
    	
    	private int layout;
    	private Activity context;
    	List<Map<String,String>> list;
    	
    	@SuppressWarnings("unchecked")
    	public FolderListAdapter(Activity context , int layout , List<Map<String,String>> list){
    		
    		super(context , layout , list);
    		
    		this.context = context;
    		this.list = list;
    		this.layout = layout;
    	}
    	
    	public View getView(int position , View convertView , ViewGroup parent){
    		
    		ViewHolder holder;

    		if (convertView == null)
    		{

    			holder = new ViewHolder();
    			
    			LayoutInflater inflater = context.getLayoutInflater();
    			convertView = inflater.inflate(layout, null);
    			
    			holder.layoutItem = (RelativeLayout)convertView.findViewById(R.id.layout_item);
    			holder.layoutItem.setBackgroundDrawable(getResources().getDrawable(R.drawable.folder_basic_02));
    			
    			holder.list_icon = (ImageView)convertView.findViewById(R.id.list_icon);
    			holder.txt_list_name = (TextView)convertView.findViewById(R.id.txt_list_name);
    			holder.txt_detail = (TextView)convertView.findViewById(R.id.txt_detail);
    			holder.file_check = (CheckBox)convertView.findViewById(R.id.file_check);
    			
    			convertView.setTag(holder);
    		}
    		else
    		{
    			holder = (ViewHolder) convertView.getTag();
    		}
    		Map<String,String> map = list.get(position);
    		
    		holder.file_check.setVisibility(View.INVISIBLE);
    		holder.txt_list_name.setText(map.get("vcFileName"));
    		holder.file_check.setFocusable(false);
			int fileSize = (int) (Long.parseLong(map.get("biFileSize"))/1024/1024);
			int playTime = (int) Long.parseLong(map.get("vcFilePlayTime"));
			holder.txt_detail.setText(map.get("dtRegDate") + "  " + fileSize + "MB " + playTime/60/60 + ":" + playTime/60%60 + ":" + playTime%60);
			
			if (map.get("vcThumbNailInfo") != null) {
				imageDownloader.download(map.get("vcThumbNailInfo"),holder.list_icon);
		    }
		    else {
		    	holder.list_icon.setImageDrawable(getResources().getDrawable(R.drawable.movie_btn));
		    }
    		
    		return  convertView;
    	}
    }
    
    static class ViewHolder
	{
		RelativeLayout layoutItem;
		ImageView list_icon;
		TextView txt_list_name;
		TextView txt_detail;
		CheckBox file_check;
	}
    
	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
		
		Map<String,String> map = totocastList.get(position);
		
		Intent intent = new Intent(TotoFunActivity.this , TotoPhotoViewActivity.class);
		intent.putExtra("position", Util.stringToInt(map.get(position+""),0));
		startActivity(intent);
	}
	
	@Override
	protected Dialog onCreateDialog (int id) {
		switch (id) {
		case PROGRESS_DIALOG:
			
			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("목록 로딩중 입니다.");
			return progressDialog;
		default:
			
			return null;
		}
	}
	
	@Override
    protected void onDestroy() {
		
		if(imageList != null && !imageList.isEmpty()){
			int size = imageList.size();
			for(int i = 0 ; i < size ; i++)
				if(imageList.get(i) != null)
					this.recycleBitmap(imageList.get(i));
		}
		
        super.onDestroy();
    }
     
    @Override
	protected void onPause() {
    	if(imageList != null && !imageList.isEmpty()){
			int size = imageList.size();
			for(int i = 0 ; i < size ; i++)
				if(imageList.get(i) != null)
					this.recycleBitmap(imageList.get(i));
		}
    	super.onPause();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
    	
    	//리트스 데이터 초기화 
    	checkList.clear();
    	imageList.clear();
    	
    	imageDownloader = new ImageDownloader();
    	//--------------------- 
    	
		super.onStart();
	}

	@Override
	protected void onResume() {
		//리트스 데이터 초기화 
    	checkList.clear();
    	imageList.clear();
    	imageDownloader = new ImageDownloader();
    	//--------------------- 
		super.onResume();
	}

	private void recycleBitmap(ImageView iv) {
    	
    	Drawable d = iv.getDrawable();
    	if (d instanceof BitmapDrawable) {
    		Bitmap b = ((BitmapDrawable)d).getBitmap();
    		b.recycle();
        }	// 현재로서는 BitmapDrawable 이외의 drawable 들에 대한 직접적인 메모리 해제는 불가능하다.
         
    	d.setCallback(null);
    }
}